<?php
/**
 * 前端店铺订单数据业务处理
 * @author ome
 * @access public
 * @copyright www.shopex.net.cn 2010
 *
 */
class ome_rpc_response_goods extends ome_rpc_response
{
	/**
	 * 商品创建
	 * @access public
	 * @param Array $sdf 商品标准结构的数据
	 * @param Object $responseObj 框架API接口实例化对象
	 * @return array('order_id'=>'订单主键ID')
	 */
	public function add($sdf, &$responseObj){
		$log = &app::get('ome')->model('api_log');
		$logTitle = '商品创建接口[货号：'. $sdf['bn'] .']';
		$logInfo = '商品创建接口：<BR>';
		$logInfo .= '接收参数 $sdf 信息：' . var_export($sdf, true) . '<BR>';
		//类别type_id
		$type_id=0;
		$oType = &app::get('ome')->model('goods_type');
		$type_id = $oType->dump(array('name'=>trim($sdf['cate_name'])),'type_id');
		if($type_id['type_id']){
			$type_id=$type_id['type_id'];
		}
		//品牌brand_id
		$brand_id=0;
		if($sdf['brand']){
		$obrand = &app::get('ome')->model('brand');
		$brand_id = $obrand->dump(array('brand_name'=>trim($sdf['brand'])),'brand_id');
		if($brand_id['brand_id']){
			$brand_id=$brand_id['brand_id'];
		}else{
			$brand['brand_name']=$sdf['brand'];
			if($obrand->save($brand)){
				$brand_id=$obrand->db->lastinsertid();
			}
			
		}
		}
		//销售类型goods_type
		$store=10000;//默认库存5 上线后改为0
		$goods_type='normal';
		if($sdf['Product_IsNoStock'] == 1){
			$goods_type='afterorder';
			$store=0;
		}
		
		$sdf['bn']=trim($sdf['bn']);
		//格式转换
				
		$post['bn']=	$sdf['bn'];
		$post['brand']['brand_id']=$brand_id;
		$post['brief']='';
		$post['category']['cat_id']	=0;
		$post['description']	='';
		$post['goods_id']='';
		$post['goods_type']=	$goods_type;//对应
		$post['name']	= $sdf['product_name'];
		$post['product']['0']['barcode']=	$sdf['barcode'];
		$post['product']['0']['bn']	=$sdf['bn'];
		$post['product']['0']['store']	= $store;
		$post['product']['0']['price']['price']['price']	= $sdf['price'];
		$post['product']['0']['price']['cost']['price']	=$sdf['price'];
		$post['product']['0']['price']['mktprice']['price']=$sdf['mktprice'];
		$post['product']['0']['price']['wholesale']['price']=$sdf['price'];
		$post['product']['0']['product_id']='';
		$post['product']['0']['status'] =	true;
		$post['product']['0']['weight'] 	=$sdf['product_weight'];
		$post['status']=	true;
		$post['type']['type_id'] 	=$type_id;
		$post['unit']	=$sdf['product_unit'];
			
			
			
			
			
		//创建商品  设置商品销售类型 start
			


		$goods = $this->_prepareGoodsData($post);
		//var_dump($goods);
		if( count( $goods['product'] ) == 0 ){
		
			$logInfo = '商品创建失败：<BR>货品未添加';
			$log->write_log($log->gen_id(), $logTitle, __CLASS__, __METHOD__, '', '', 'response', 'fail', $logInfo);
			return false;
		}
			
		$ret = array();
		$bar = array();
		$oGoods = &app::get('ome')->model('goods');
		if($oGoods->checkProductBn($goods['bn'], $goods['goods_id'])){
				
			$logInfo = '商品创建失败：<BR>您所填写的商品编号已被使用，请检查！';
			//$log->write_log($log->gen_id(), $logTitle, __CLASS__, __METHOD__, '', '', 'response', 'fail', $logInfo);
			return false;
		}
		if($oGoods->checkBarcode($goods['barcode'], $goods['goods_id'])){
				
			$logInfo = '商品创建失败：<BR>所填写的商品条形码已被使用，请检查！';
			//$log->write_log($log->gen_id(), $logTitle, __CLASS__, __METHOD__, '', '', 'response', 'fail', $logInfo);
			return false;
		}
		foreach($post['product'] as $k=>$v){
			if($v['bn'] == ''){

				$logInfo = '商品创建失败：<BR>货号不能为空，请检查！';
				//$log->write_log($log->gen_id(), $logTitle, __CLASS__, __METHOD__, '', '', 'response', 'fail', $logInfo);
				return false;
			}
			if($oGoods->checkProductBn($v['bn'], $goods['goods_id'])){

				$logInfo = '商品创建失败：<BR>您所填写的货号已被使用，请检查！';
				//$log->write_log($log->gen_id(), $logTitle, __CLASS__, __METHOD__, '', '', 'response', 'fail', $logInfo);
				return false;
			}else{
				$ret[$v['bn']] = $v['bn'];
			}
			if($oGoods->checkBarcode($v['barcode'], $goods['goods_id'])){
				$logInfo = '商品创建失败：<BR>您所填写的条形码已被使用，请检查！';
			//	$log->write_log($log->gen_id(), $logTitle, __CLASS__, __METHOD__, '', '', 'response', 'fail', $logInfo);
				return false;
			}
			foreach(kernel::servicelist('ome.product') as $name=>$object){
				if(method_exists($object, 'checkProductByBn')){
					$checkBn = $object->checkProductByBn($v['bn']);
					if((!$v['product_id'] && $checkBn) || ($v['product_id'] && $checkBn && $checkBn != $v['product_id'])){

						$logInfo = '商品创建失败：<BR>您所填写的货号已被其它商品模块使用！';
						//$log->write_log($log->gen_id(), $logTitle, __CLASS__, __METHOD__, '', '', 'response', 'fail', $logInfo);
						return false;
						break;
					}
				}
			}
			if ($k==0)
				$goods['barcode'] = $v['barcode'];
		}
			
		if(count($ret) != count($post['product'])){
				
			$logInfo = '商品创建失败：<BR>您所填写的货号存在重复，请检查！';
			//$log->write_log($log->gen_id(), $logTitle, __CLASS__, __METHOD__, '', '', 'response', 'fail', $logInfo);
			return false;
		}
			
		/*$goods_detail = $oGoods->dump(array('name'=>trim($goods['title'])),'*');
		if($goods_detail){
			$logInfo = '商品创建失败：<BR>商品名称已存在';
			$log->write_log($log->gen_id(), $logTitle, __CLASS__, __METHOD__, '', '', 'response', 'fail', $logInfo);
			return false;
		}*/
			
		//增加商品保存前的扩展  暂时注释
// 		foreach(kernel::servicelist('ome.goods') as $o){
// 			if(method_exists($o,'pre_save')){
// 				$o->pre_save($goods);
// 			}
// 		}
			
		
		if(!$oGoods->save($goods)){
			$m = $oGoods->db->errorinfo();
			kernel::log("errmsg = ".$m);

		}
			
		//增加商品保存后的扩展  暂时注释
// 		foreach(kernel::servicelist('ome.goods') as $o){
// 			if(method_exists($o,'after_save')){
// 				$o->after_save($goods);
// 			}
// 		}		
		
			
		//分配仓库 默认库存5  start 上线后去掉
		$branch_id=1;
		
		//零库存商品仓库为2 默认库存为0
// 		if($sdf['Product_IsNoStock'] == 1){
// 			$branch_id=2;
// 			$store=0;
// 		}

		$oBranchproduct = &app::get('ome')->model('branch_product');
		$oProduct = &app::get('ome')->model('products');
		$product_id = $oProduct->dump(array('bn'=>$sdf['bn']),'product_id');
		if( $product_id['product_id'] ){
			
			$branchproduct['branch_id']=$branch_id;
			$branchproduct['product_id']=$product_id['product_id'];
			$branchproduct['store']=$store;
			$branchproduct['store_freeze']=0;
			$branchproduct['last_modified ']='';
			$branchproduct['arrive_store ']=0;
			$branchproduct['safe_store']=1;
//			var_dump($branchproduct);
			if(!$oBranchproduct->save($branchproduct)){
				kernel::log("分配仓库失败，bn:".$sdf['bn']);
				//echo 'ok';
			}
		}
		//分配仓库 end
		$log->write_log($log->gen_id(), $logTitle, __CLASS__, __METHOD__, '', '', 'response', 'success', $logInfo);
		return true;
	}

	function _prepareGoodsData( &$data ){
		$goods = $data;
		//$goods['adjunct'] = $data['adjunct'];
		//$goods['image_default_id'] = $data['image_default'];
		foreach( explode( '|', $data['keywords']) as $keyword ){
			$goods['keywords'][] = array(
					'keyword' => $keyword,
					'res_type' => 'goods'
			);
		}
		if( $goods['spec'] ){
			$goods['spec'] = unserialize($goods['spec']);
		}else{
			$goods['spec'] = null;
		}
		//处理配件

		if( !$goods['min_buy'] )unset( $goods['min_buy'] );
		if( !$goods['brand']['brand_id'] )unset( $goods['brand'] );
		//        $images = array();
		//        foreach( (array)$goods['images'] as $imageId ){
		//            $images[] = array(
		//                'target_type'=>'goods',
		//                'image_id'=>$imageId,
		//                );
		//        }
		//        $goods['images'] = $images;
		//        unset($images);
		if(isset($goods['adjunct']['name'])){
			foreach($goods['adjunct']['name'] as $key => $name){
				$aItem['name'] = $name;
				$aItem['type'] = $goods['adjunct']['type'][$key];
				$aItem['min_num'] = $goods['adjunct']['min_num'][$key];
				$aItem['max_num'] = $goods['adjunct']['max_num'][$key];
				$aItem['set_price'] = $goods['adjunct']['set_price'][$key];
				$aItem['price'] = $goods['adjunct']['price'][$key];
				if($aItem['type'] == 'goods') $aItem['items']['product_id'] = $goods['adjunct']['items'][$key];
				else $aItem['items'] = $goods['adjunct']['items'][$key];//.'&dis_goods[]='.$aData['goods_id']
				$aAdj[] = $aItem;
			}
		}
		$goods['adjunct'] = $aAdj;

		$goods['product'][key($goods['product'])]['default'] = '1';
		foreach( $goods['product'] as $prok => $pro ){
			if( !$pro['product_id'] || substr( $pro['product_id'],0,4 ) == 'new_' )
				unset( $goods['product'][$prok]['product_id'] );
			if( $pro['status'] != 'true' )
				$goods['product'][$prok]['status'] = 'false';
			$mprice = array();
			if( $pro['weight'] === '' )
				$goods['product'][$prok]['weight'] = '0';
			if( $pro['store'] === '' )
				$goods['product'][$prok]['store'] = null;
			//  foreach( (array)$pro['price']['member_lv_price'] as $mLvId => $mLvPrice )
			//                if( $mLvPrice )
			//                    $mprice[] = array( 'level_id'=>$mLvId,'price'=>$mLvPrice );
			//$goods['product'][$prok]['price']['member_lv_price'] = $mprice;
			foreach( array('mktprice','cost','price','wholesale') as $pCol ){
				if( !$pro['price'][$pCol]['price'] && $pro['price'][$pCol]['price'] !== 0 ){
					$goods['product'][$prok]['price'][$pCol]['price'] = '0';
				}
			}
			$goods['product'][$prok]['unit'] = $goods['unit'];
		}
		if( !$goods['tag'] ) $goods['tag'] = array();
		return $goods;
	}

}
?>